﻿import React from 'react';
import {Link, hashHistory} from 'react-router';
import { Button, Icon,  Table, Spin, Popconfirm, message } from 'antd';
import QueryForm from './queryForm'
import classNames from 'classnames';
import {connect} from 'react-redux'
import SearchInput from '../../components/SearchInput'
import './index.css'
import { studentsQuery, studentsDelete } from '../../actions'

const ButtonGroup = Button.Group;

class StudentQuery extends React.Component {

	constructor(props){
		super(props);
		this.state = {
			selectedRowKeys:[],
			searchFromVisible: false,
      batchDeleteDisabled: true,
      parameter:{},
		};
	}

  componentWillMount () {
    console.log('StudentQuery.componentWillMount')
    const param = {
      pageSize: 10,
      current: 1,
    };
    this.setState({parameter: param});
    this.props.dispatch(studentsQuery.request()(param));
  }

  handleTableChange(pagination, filters, sorter) {
    const param = {
      ...this.state.parameter,
      pageSize: pagination.pageSize || 10,
      current: pagination.current || 1,
      sortField: sorter.field,
      sortOrder: sorter.order,
      ...filters,
    };
    this.props.dispatch(studentsQuery.request()(param));
  }

	onAdvancedSearchClick() {
		this.setState({searchFromVisible:!this.state.searchFromVisible});
	}

	onSelectChange(selectedRowKeys) {
		this.setState({ selectedRowKeys });
	}

  onStudentDetailClick(studentId) {
    hashHistory.push({ pathname: '/order/checkOne', state: { studentId, mode:'Read', back:'/student/query' } });
  }

  onStduentDelete(id) {
    this.props.dispatch(studentsDelete.request()({ids:[id]}))
  }

  onSearchClick(value) {
    console.log("studentId=", value);
    const param = {...this.state.parameter, studentId: value};
    this.props.dispatch(studentsQuery.request()(param));
  }

  onQueryClick(value) {
    const param = {...this.state.parameter, ...value};
    this.props.dispatch(studentsQuery.request()(param));
  }

  onStduentsDelete() {
    this.props.dispatch(studentsDelete.request()({ids:this.state.selectedRowKeys}))
  }

	render() {

		const rowSelection = {
			selectedRowKeys:this.state.selectedRowKeys,
			onChange: this.onSelectChange.bind(this),
		};

		let { data, loading, pagination } = this.props;
    const paginationTable = {
      showSizeChanger:true,
      pageSizeOptions:['10', '20', '50', '100'],
      pageSize:10,
      current:1,
      total:0,
      ...pagination
    };
    let majorFilter = [];
    let degreeFilter = [];
    data.forEach((student) => {
      let foundMajorNameIndex = majorFilter.findIndex((value) => {
        value.text == student.majorName
      });
      if (student.majorName && foundMajorNameIndex == -1) {
        majorFilter.push({text: student.majorName, value: student.majorName});
      }
      let foundDegreeIndex = degreeFilter.findIndex((value) => {
        value.text == student.degree
      });
      if (student.degree && foundDegreeIndex == -1) {
        degreeFilter.push({text: student.degree, value: student.degree});
      }
    });

    const columns = [
      {
        title: '学号',
        dataIndex: 'id',
        sorter: true,
        width: '10%',
        sorter: true,
      },
      {
        title: '姓名',
        dataIndex: 'name',
        width: '10%',
      },
      {
        title: '专业',
        dataIndex: 'majorName',
        width: '20%',
        filters: majorFilter,
      },
      {
        title: '学历',
        dataIndex: 'degree',
        width: '10%',
        filters:degreeFilter
      },
      {
        title: '入学年份',
        dataIndex: 'enterDate',
        width: '10%',
        sorter: true,
      },
      {
        title: '毕业年份',
        dataIndex: 'outDate',
        width: '10%',
        sorter: true,
      },
      {
        title: '签约状态',
        dataIndex: 'statusDesc',
        width: '15%',
      },
      {
        title: '操作',
        key: 'operation',
        render:(text, record) => (
          <ButtonGroup>
            <Button  type="ghost" onClick={this.onStudentDetailClick.bind(this, record.id, )}>查看</Button>
            <Popconfirm title="确定要删除该学生数据吗？" onConfirm={this.onStduentDelete.bind(this, record.id)} onCancel={()=>{}}>
              <Button  type="ghost">删除</Button>
            </Popconfirm>
          </ButtonGroup>
        ),
        width: '15%'
      }
    ];
    console.log("paginationTable = %o, pagination = %o", paginationTable, pagination, this.state.batchDeleteDisabled);
		// 表格的列控制
		return (
			<div>
				<QueryForm visible={this.state.searchFromVisible} onQueryClick={this.onQueryClick.bind(this)}/>
				<div style={{ marginTop: 24, marginBottom: 16 }} className="clearfix">
					<div className="pull-left">
            <Popconfirm title="确定要删除这些学生的数据吗？" onConfirm={this.onStduentsDelete.bind(this)} onCancel={()=>{}}>
						  <Button disabled={(this.state.selectedRowKeys.length == 0)} type="primary">批量删除</Button>
             </Popconfirm>
					</div>
					<div className="pull-right">
						<SearchInput placeholder="请输入学号" onSearch={this.onSearchClick.bind(this)} style={{ width: 200 }} />
						<a style={{marginLeft:8}} onClick={this.onAdvancedSearchClick.bind(this)} type="primary" >高级搜索</a></div>
				</div>
        <Spin spinning={loading}>
          <Table rowSelection={rowSelection} rowKey='id' pagination={paginationTable} columns={columns} dataSource={data} onChange={this.handleTableChange.bind(this)} />
        </Spin>
      </div>
    );
	}
}

function mapStateToProps(state) {
  return {
    data: state.student.students.data,
    loading: state.student.loading,
    pagination:state.student.students.pagination,
  };
}

export default connect(mapStateToProps)(StudentQuery)
